package cn.itcast.session;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.mail.iap.Response;

public class SessionDemo01 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {


		//		test2(request,response);
		test1(request,response);   

	}
	private void test2(HttpServletRequest request,HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		HttpSession session = request.getSession();

		String sessionId = session.getId();
		Cookie cookie = new Cookie("JSESSIONID",sessionId);
		cookie.setMaxAge(30*60);
		cookie.setPath("/day07");
		response.addCookie(cookie);
		session.setAttribute("data", "data"); 
	}
	private void test1(HttpServletRequest request,HttpServletResponse response) {
		// 用户禁用cookie

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		/**
		 * 这种情况 , 服务器默认创建的session是没有回话期限的.关闭浏览器就丢失 ;
		 * 操作步骤: 1. 用户访问 day/index.jsp  点击orderServlet 带过来数据 关闭浏览器
		 * 
		 * 			2.  用户访问   buyServlet   ,查看发现回写浏览器的数据为null  
		 * 解决方案: 见 test2()
		 */
		HttpSession session = request.getSession();



		//		request.getSession(false);   // 只获取不新建
		session.setAttribute("data", "洗衣机2500"); 

		//		session.invalidate();  // 设置session失效
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
